<template>
  <div class="dropdown" @click.stop="toggleDropdown" :class="theme">
    <button class="dropdown-toggle">
      {{ selectedOption || defaultText }}
      <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" v-if="isOpen">
      <li
        v-for="(name,i) in options"
        :key="name"
        @click.stop="selectOption(name,i)"
      >
        <span class="dropdown-item">{{ name }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
const props = defineProps({
  theme: {
    type: String,
    default: "purple",
  },
  index: {
    type: Number,
    default: 0,
  },
  options: {
    type: Array,
    default: () => [],
  },
});
const defaultText = computed(() => {
  return props.options[props.index];
});
const isOpen = ref(false);
const selectedOption = ref(null);

const toggleDropdown = () => {
  isOpen.value = !isOpen.value;
};

const emit = defineEmits(["selected"]);
const selectOption = (name,i) => {
  isOpen.value = false;
  emit("selected", name,i);
};

window.addEventListener("click", () => {
  if (isOpen.value) {
    isOpen.value = false;
  }
});
</script>

<style lang="scss" scoped>
.dropdown {
  position: relative;
  display: inline-block;
  user-select: none;
  margin-left: 30px;
}
.purple {
  .dropdown-toggle {
    border: 1px solid #184e97;
    background: #1a2660;
  }
  .dropdown-menu {
    background: linear-gradient(180deg, #1a2660 0%, #384e99 100%);
    border: 1px solid rgba(21, 154, 255, 0.35);
  }
  .dropdown-item:hover {
    color: #879fff;
  }
}

.blue {
  .dropdown-toggle {
    background-color: rgba(#159aff, 0.26);
    border: 1px solid rgba(21, 154, 255, 0.35);
  }
  .dropdown-menu {
    background: linear-gradient(180deg, #00224a 0%, #09518b 100%);
    border: 1px solid rgba(21, 154, 255, 0.35);
  }
  .dropdown-item:hover {
    color: #87b9ff;
  }
}

.dropdown-toggle {
  width: 130px;
  height: 29px;
  font-size: 16px;
  cursor: pointer;
  text-align: left;
  font-family: MicrosoftYaHei;
  font-size: 14px;
  color: #d0deee;
  text-align: center;
  font-style: normal;
}

.caret {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 2px;
  vertical-align: middle;
  border-top: 4px dashed #fff;
  border-right: 4px solid transparent;
  border-left: 4px solid transparent;
}

.dropdown-menu {
  position: absolute;
  background: linear-gradient(180deg, #1a2660 0%, #384e99 100%);
  width: 130px;
  border: 1px solid rgba(21, 154, 255, 0.35);
  z-index: 1;
  list-style: none;
  padding: 0;
  margin: 0;
  left: 0;
  top: 100%;
  z-index: 99;
}

.dropdown-item {
  padding: 8px;
  text-decoration: none;
  display: block;
  font-family: MicrosoftYaHei;
  font-size: 14px;
  color: #d0deee;
  line-height: 22px;
  text-align: center;
  transition: all 0.3s ease-in-out;
  cursor: pointer;
}

.dropdown-item:hover {
  color: #879fff;
}
</style>
